<template>
  <nav class="top-nav">

    <div class="nav-menu">
      <router-link to="/main" class="logo">
        <img src="/src/assets/images/logo-topbar.gif" alt="宠物商店">
      </router-link>

      <!-- //购物车 Cart 在这儿 -->
      <!-- 根据当前路由决定是否显示购物车链接 -->



      <!-- //登录 Sign In 登出 Sign Out 和 My Account  在这里 -->

      <template v-if="!userStore.isAuthenticated">
      <router-link to="/login">Sign In</router-link>
      <img src="/src/assets/images/separator.gif" class="separator"/>
     </template>

     <template v-else>
      <a href="/main" @click.prevent="userStore.logout">Sign Out</a>
      <img src="/src/assets/images/separator.gif" class="separator"/>

      <div class="account-dropdown">
        <div class="dropdown" @mouseover="showDropdown = true" @mouseleave="showDropdown = false">
          <span class="dropdown-title">My Account</span>
          <ul v-if="showDropdown" class="dropdown-content">
            <li>
              <router-link to="/userinfo">Check Account</router-link>
            </li>
            <li>
              <router-link :to="{ name: 'getUserOrder', params: { userId: userStore.user.userid } }">
                My History Orders
              </router-link>
            </li>
            <li>
            <router-link :to="{ name: 'Cart', params: { userId: userStore.user.userid } }">
              <img src="/src/assets/images/cart.gif" alt="购物车" class="cart-icon">购物车
            </router-link>
            </li>
          </ul>
        </div>
      </div>
      <img src="/src/assets/images/separator.gif" class="separator"/>
    </template>      

      <a href="help.html">?</a>

      <div class="search-box" ref="searchBoxRef">
        <input
            v-model="searchKeyword"
            type="text"
            placeholder="搜索商品..."
            @keyup.enter="handleSearch"
        />
        <button
            @click="handleSearch"
            class="search-btn"
        >搜索</button>
        <div v-if="searchResults?.length > 0" class="search-results-layer">
          <div
              v-for="product in searchResults"
              :key="product.productId"
              class="result-item"
          >
            <router-link :to="{ name: 'ProductDetail', params: { productId: product.productId } }">
              {{ product.name }}
            </router-link>
          </div>
        </div>
      </div>
    </div>

    <div class="quick-links-container">
      <div class="quick-links">
        <template v-for="(category, index) in categories" :key="category.id">
          <router-link :to="{name:'ProductList',params:{categoryId: category.id}}">
            <img :src="`/src/assets/images/${category.icon}`" :alt="category.name"/>
          </router-link>
          <img v-if="index < categories.length - 1" src="/src/assets/images/separator.gif" class="separator"/>
        </template>
      </div>
    </div>
  </nav>
</template>

<script setup>
import {ref, watchEffect, onMounted, onUnmounted} from 'vue'
import {useRoute,useRouter } from 'vue-router'
import service from '@/api/request0.js'

import { useUserStore } from '@/stores/userStore'
const userStore = useUserStore();
//lrd 85-98行
// 修改导入路径，从 vue 中导入 computed
import {computed} from 'vue';

// 获取当前路由信息
const route = useRoute();

// 定义一个计算属性，根据当前路由判断是否显示购物车链接
const shouldShowCartLink = computed(() => {
  // 这里可以根据需要添加更多不需要显示购物车链接的路由路径
  const hiddenRoutes = ['/add-item', '/query-all-items', '/update-item', '/delete-item', '/cart'];
  console.log('当前路由路径:', route.path); // 输出当前路由路径
  return !hiddenRoutes.includes(route.path);
});

//My Account下拉框默认为不打开
const showDropdown = ref(false);

// 分类数据
const categories = [
  {id: 'FISH', icon: 'sm_fish.gif', name: '鱼类'},
  {id: 'DOGS', icon: 'sm_dogs.gif', name: '犬类'},
  {id: 'REPTILES', icon: 'sm_reptiles.gif', name: '爬行类'},
  {id: 'CATS', icon: 'sm_cats.gif', name: '猫类'},
  {id: 'BIRDS', icon: 'sm_birds.gif', name: '鸟类'}
]

// const route = useRoute()
const router = useRouter()
const searchResults = ref([])
const searchKeyword = ref('')
const searchBoxRef = ref(null)

// 点击外部关闭搜索框
const handleClickOutside = (event) => {
  if (searchBoxRef.value && !searchBoxRef.value.contains(event.target)) {
    searchResults.value = []
    searchKeyword.value = ''
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

watchEffect(async () => {
  try {
    if (searchKeyword.value) {
      searchResults.value = await service.get(`/search/${encodeURIComponent(searchKeyword.value)}`)
    } else {
      searchResults.value = []
    }
  } catch (error) {
    console.error('搜索失败:', error);
    searchResults.value = []
  }
})
const handleSearch = (e) => {
  e.preventDefault();
  if (searchKeyword.value?.trim()) {
    router.push({
      name: 'ProductSearch',
      params: { keyword: encodeURIComponent(searchKeyword.value.trim()) }
    });
  }
}
</script>


/* 样式 */
<style scoped>
.quick-links-container {
  background: #f8f9fa;
  padding: 12px 20px;
  width: 100%;
  margin-top: 8px;
}

.top-nav {
  flex-direction: column;
}

.quick-links {
  justify-content: center;
  gap: 16px;
}

.account-dropdown {
  position: relative;
  display: inline-block;
}

.dropdown {
  cursor: pointer;
  padding: 10px;
  border-radius: 5px;
}

.dropdown-title{
  color:white;
}

.dropdown-content {
  display: block;
  position: absolute;
  min-width: 160px;
  z-index: 1;
  margin-block-start: 0;
  background-color: #4d6986;
  padding-left: 20px;
}

.dropdown-content li {
  padding:5px 5px;
  list-style: none;
}

.dropdown-content li:hover {
  background-color: #2c3e50;
}

.router-link-exact-active {
  color: #007bff;
}

.nav-menu {
  margin-left: 0;
}

.top-nav {
  display: flex;
  align-items: center;
  background: #2c3e50;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.logo img {
  height: 60px;

}

.nav-menu {
  flex: 1;
  display: flex;
  margin-left: 30px;
  gap: 8px;
  align-items: center;
}

.quick-links {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quick-links img {
  height: 24px;
  vertical-align: middle;
}

.separator {
  margin: 0 4px;
}

input, .search-btn {
  background: rgba(255,255,255,0.1);
  border: 1px solid #34495e;
  color: #ecf0f1;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.search-btn:hover {
  background: rgba(255,255,255,0.2);
}

.search-results-layer {
  background: #34495e;
  border: 1px solid #2c3e50;
  width: 200px;
  left: auto;
  right: 0;
  transform: translateX(16px);
  border-radius: 4px;
}

.search-box {
  display: flex;
  gap: 1px;
  margin-left: auto;
  position: relative;
}

input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 200px;
}


.search-results-layer {
  position: absolute;
  top: calc(100% + 5px);
  background: white;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-height: 400px;
  overflow-y: auto;
  width: 200px;
  margin-left: -1px;
}

.result-item {
  padding: 12px;
  border-bottom: 1px solid #eee;
  transition: background 0.2s;
}

.result-item:hover {
  background: #f8f8f8;
}

.nav-menu {
  font-size: 1.1rem;
  gap: 12px;
}

.nav-menu a {
  color: #ecf0f1;
  font-weight: bold;
  text-decoration: none;
  transition: color 0.2s;
}

.result-item a {
  color: #2c3e50;
}
.nav-menu a:hover {
  color: #ffffff;
}

.cart-icon {
  height: 36px;
  vertical-align: middle;
}
.search-box {
  position: relative;
}

.search-results-layer {
  right: 0;
  margin-left: 0;
  transform: none;
  width: calc(100% + 1px);
}
</style>